<?php

namespace app\admin\controller\user;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use app\common\library\Auth;
use Exception;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 区域合伙人管理
 *
 * @icon fa fa-user
 */
class Region extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    //当前登录管理员所有子组别
    protected $childrenGroupIds = [];
    //当前组别列表数据
    protected $addresslist = [];
    protected $addressdata = [];
    //无需要权限判断的方法
    protected $noNeedRight = ['roletree'];
   /* public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }*/

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        /*$this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $addressList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($addressList);
        $addressList = [];
        if ($this->auth->isSuperAdmin()) {
            $addressList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        } else {
            $groups = $this->auth->getGroups();
            $groupIds = [];
            foreach ($groups as $m => $n) {
                if (in_array($n['id'], $groupIds) || in_array($n['pid'], $groupIds)) {
                    continue;
                }
                $addressList = array_merge($addressList, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
                foreach ($addressList as $index => $item) {
                    $groupIds[] = $item['id'];
                }
            }
        }
        $groupName = [];
        foreach ($addressList as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }

        $this->addresslist = $addressList;
        $this->addressdata = $groupName;
        $this->assignconfig("admin", ['id' => $this->auth->id, 'group_ids' => $this->auth->getGroupIds()]);
        $this->view->assign('addressdata', $this->addressdata);*/
    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('regionLevel')//'group',
                ->where($where)
                ->where(["identity"=>2])//"type"=>1,
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $v["address"]=model('app\common\model\Area')->whereIn("id",$v["region_address"])->column("GROUP_CONCAT(name)")[0]??'';
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $cacheTime = 60; // 1.1.7升级 查询缓存
            /*$tree = [];
            $packData = [];
            $cacheTime = 60; // 1.1.7升级 查询缓存
            // 把数组的引用赋给新数组
            foreach (collection(model('app\common\model\Area')->field('id,pid,name,code,zip,level')->cache(true, $cacheTime)->select())->toArray() as $vo) {
                $packData[$vo['id']] = $vo;
            }
            // 获取树状结构的数组
            foreach ($packData as $key => $val) {
                if ($val['pid'] == 0)
                    $tree[] = &$packData[$key];
                else
                    if($val['level'] === 3){
                        $packData[$val['pid']]['area'][] = &$packData[$key];
                    }else{
                        $packData[$val['pid']]['city'][] = &$packData[$key];
                    }
            }*/
            $ids=\app\common\model\User::field("id,GROUP_CONCAT(region_address) region_address")->where(["identity"=>2,"region_status"=>1])->find();
            if(!empty($ids) && !empty($ids["region_address"])){
                $ids=explode(",",$ids["region_address"]);
            }else{
                $ids=[];
            }
            $address=model('app\common\model\Area')->field('id,pid,name,code,zip,level')->cache(true, $cacheTime);
            $address=$address->select();
            $ruleList=collection($address)->toArray();
            $nodeList = [];
            Tree::instance()->init($ruleList);
            $ruleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
            $hasChildrens = [];
            $selected=[];
            foreach ($ruleList as $k => $v)
            {
                if ($v['haschild'])
                    $hasChildrens[] = $v['id'];
            }
            foreach ($ruleList as $k => $v) {
                $state = array('selected' => in_array($v['id'], $selected) && !in_array($v['id'], $hasChildrens),"disabled"=>false);
                if(!empty($ids)){
                    $state["disabled"]=in_array($v['id'], $ids);
                }
                $nodeList[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['name']), 'type' => 'menu', 'state' => $state);
            }
            $this->assign("nodeList", $nodeList);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $data=[
                "region_address"=>$params["rules"],
                "region_level_id"=>$params["region_level_id"],
                "identity"=>2,
            ];
            $row=$this->model->get($params["user_id"]);
            if(!empty($row)){
                $result = $row->allowField(true)->save($data);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $cacheTime = 60; // 1.1.7升级 查询缓存
            /*$tree = [];
            $packData = [];
            $cacheTime = 60; // 1.1.7升级 查询缓存
            // 把数组的引用赋给新数组
            foreach (collection(model('app\common\model\Area')->field('id,pid,name,code,zip,level')->cache(true, $cacheTime)->select())->toArray() as $vo) {
                $packData[$vo['id']] = $vo;
            }
            // 获取树状结构的数组
            foreach ($packData as $key => $val) {
                if ($val['pid'] == 0)
                    $tree[] = &$packData[$key];
                else
                    if($val['level'] === 3){
                        $packData[$val['pid']]['area'][] = &$packData[$key];
                    }else{
                        $packData[$val['pid']]['city'][] = &$packData[$key];
                    }
            }*/
            $not_address=\app\common\model\User::field("id,GROUP_CONCAT(region_address) region_address")
                ->where(["identity"=>2,"region_status"=>1])->where("id <>".$ids)->find();
            if(!empty($not_address) && !empty($not_address["region_address"])){
                $not_address=explode(",",$not_address["region_address"]);
            }else{
                $not_address=[];
            }
            $address=model('app\common\model\Area')->field('id,pid,name,code,zip,level')->cache(true, $cacheTime);
            $address=$address->select();
            $ruleList=collection($address)->toArray();
            $nodeList = [];
            Tree::instance()->init($ruleList);
            $ruleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
            $hasChildrens = [];
            $selected=[];
            foreach ($ruleList as $k => $v)
            {
                if ($v['haschild'])
                    $hasChildrens[] = $v['id'];
            }
            if(!empty($row) && !empty($row["region_address"])){
                $selected=explode(",",$row["region_address"]);
            }
            foreach ($ruleList as $k => $v) {
                $state = array('selected' => in_array($v['id'], $selected) && !in_array($v['id'], $hasChildrens),"disabled"=>false);
                if(!empty($not_address)){
                    $state["disabled"]=in_array($v['id'], $not_address);
                }
                $nodeList[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['name']), 'type' => 'menu', 'state' => $state);
            }
            $this->assign("nodeList", $nodeList);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $data=[
                "region_address"=>$params["rules"],
                "region_level_id"=>$params["region_level_id"],
                //"identity"=>2,
            ];
            $result = $row->allowField(true)->save($data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            /*foreach ($list as $item) {
                $count += $item->delete();
            }*/
            $count=$this->model->where($pk, 'in', $ids)->update([
                "identity"=>0,
                "region_address"=>'',
                "region_level_id"=>0,
            ]);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    /**
     * 禁用
     * */
    public function operation(){
        if (!$this->request->param("id")) $this->error('id为空');
        $param=$this->request->param();
        $row = $this->model->get($param["id"]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($param["region_status"]=="1"){
            $param["remark"]='';
            $not_address=\app\common\model\User::field("id,GROUP_CONCAT(region_address) region_address")
                ->where(["identity"=>2,"region_status"=>1])
                ->where("id <>".$param["id"])->find();
            if(!empty($not_address)){
                $region_address=explode(",",$row["region_address"]);
                $not_address=explode(",",$not_address["region_address"]);
                if(array_intersect($region_address,$not_address)){
                    $this->error(__('该用户所选区域已有合伙人，请先禁用合伙人或修改区域'));
                }
            }
        }
        $result = $row->allowField(true)->save($param);
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }

}
